﻿using System;
using System.Web;
using System.Web.Mvc;
using System.Web.Routing;
using ClassLibrary;
using HinduShop.DbClassLib;
using HinduShop.Domain.Models;
using HinduShop.UI.Binders;
using NHibernate;
using Ninject;

namespace HinduShop.UI
{
    // Примечание: Инструкции по включению классического режима IIS6 или IIS7 
    // см. по ссылке http://go.microsoft.com/?LinkId=9394801

    public class MvcApplication : System.Web.HttpApplication
    {
        SessionManager sessionManager = new SessionManager();

        public static void RegisterGlobalFilters(GlobalFilterCollection filters)
        {
            filters.Add(new HandleErrorAttribute());
        }

        public static void RegisterRoutes(RouteCollection routes)
        {
            routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

            routes.MapRoute(
                "Default", // Имя маршрута
                "{controller}/{action}/{id}", // URL-адрес с параметрами
                new { controller = "StoreManager", action = "Index", id = UrlParameter.Optional } // Параметры по умолчанию
            );

        }

        protected void Application_Start()
        {
            AreaRegistration.RegisterAllAreas();

            RegisterGlobalFilters(GlobalFilters.Filters);
            RegisterRoutes(RouteTable.Routes);

            ModelBinders.Binders.Add(typeof(Cart), new CartModelBinder());

            ControllerBuilder.Current.SetControllerFactory(new NinjectControllerFactory());

           // AutoMapperConfigurator.Configure();
        }

        public static ISession CurrentSession
        {
            get { return (ISession)HttpContext.Current.Items["currents.session"]; }
            set { HttpContext.Current.Items["current.session"] = value; }
        }

        protected void Application_BeginRequest(object sender, EventArgs e)
        {
            CurrentSession = sessionManager.OpenSession();
        }

        protected void Application_EndRequest(object sender, EventArgs e)
        {
            if (CurrentSession != null)
            {
                CurrentSession.Dispose();
            }
        }
    }
}